<?php

namespace app\api\service\pay;

use app\api\model\activity\Goods as GoodsModel;
use app\api\service\coupon\MyCoupon;
use app\api\service\lucky\TwiceRward;
use app\common\enum\order\OrderStatus;
use app\common\enum\order\PayStatus;
use app\common\model\activity\CarReward;
use app\common\model\activity\RewardConfig;
use app\common\model\Order;
use app\job\LuckyBagQueue;
use app\job\LuckyBagReward;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;

class ActivityOrderPay extends PaySuccess
{

    private  $order_no = '';
    private  $box_index = '';

    public function onSuccess(array $payment, int $payType): bool
    {
        Db::startTrans();
        try{
            // 商品更新
            $order = Order::where('order_no', $payment['order_no'])->find();
            GoodsModel::update(['status' => 1,'sell_time' => time()], ['order_id' => $order->order_id]);
            $order->pay_status   = PayStatus::SUCCESS;
            $order->trans_no     = $payment['transaction_id'];
            $order->order_status = OrderStatus::COMPLETED;
            $order->pay_time     = time();
            $order->save();

             //处理车位逻辑  避免车位失败阻止订单支付失败
             self::presentCar($order);
//             if(!$handle){
//                 throw new Exception('车位处理失败');
//             }

            //核销优惠券
            if($order->coupon_id > 0){
                //核销优惠券
                Log::channel('wxpay')->info('抽选订单核销优惠券：'.$order->coupon_id);
                $res = app(MyCoupon::class)->destruction($order->user_id,$order->coupon_id,$source_order->order_id ?? 0,$order->coupon_num);
                if(!$res){
                    return false;
                }
            }
            Db::commit();
            $this->order_no = $payment['order_no'];
            return true;
        }catch (\Exception $e){
            Db::rollBack();
            Log::channel('wxpay')->info('订单号：'.$payment['order_no'].'支付失败');
            Log::channel('wxpay')->info('失败原因：'.$e->getMessage());
            return false;
        }

    }

    //赠送车位处理
    public static function presentCar($order): bool
    {
        Log::channel('wxpay')->info('开始处理车位奖');
        try {
            $reward_configs = RewardConfig::where([
                'activity_id' => $order->activity_id,
                'reward_type' => RewardConfig::REWARD_TYPE_CAR
            ])->select()->toArray();
            if(!empty($reward_configs)){
                foreach ($reward_configs as $reward_config){
                    //查看订单商品中是否有指定等级 有则处理,无则忽略
                    $order_goods = (new GoodsModel)->where([
                        'order_id' => $order->order_id,
                        'reward_type' => $reward_config['level']
                    ])->select()->toArray();
                    if(!empty($order_goods)){
                        $car_reward_num = CarReward::where('reward_id',$reward_config['reward_id'])
                            ->where('box_index', $order_goods[0]['box_index'])
                            ->count();
                        $condition = [
                            'activity_id' => $order->activity_id,
                            'reward_type' => $reward_config['level'],
                            'user_id' => $order->user_id,
                            'status' => 1,
                            'box_index' => $order_goods[0]['box_index'],
                            'car_reward_tip' => 0,
                        ];
                        $goods_ids = (new GoodsModel)->where($condition)->column('goods_id');
                        $cnt = count($goods_ids);    //拥有未标识等级商品数量
                        Log::channel('wxpay')->info($order->user_id.':拥有未标识等级商品数量#'.$cnt);
                        if($car_reward_num < $reward_config['car_num']){
                            Log::channel('wxpay')->info('22222');
                            $gain_car_num = intval($cnt / $reward_config['reach_num']);
                            Log::channel('wxpay')->info('车位标识id#'.$reward_config['reward_id'].'#'.$order->user_id.':获得车位数量#'.$gain_car_num);
                            if($gain_car_num > 0){
                                $insert_data = [];
                                foreach (range(1,$gain_car_num) as $car_index){
                                    $insert_data[] = [
                                        'activity_id' => $order->activity_id,
                                        'user_id' => $order->user_id,
                                        'box_index' => $order_goods[0]['box_index'],
                                        'level' => $reward_config['level'],
                                        'reward_id' => $reward_config['reward_id'],
                                        'order_no' => $order->order_no,
                                    ];
                                }
                                (new CarReward)->saveAll($insert_data);
                                //同时更新reach_num * gain_car_num个订单商品
                                $need_goods_id = array_slice($goods_ids,0,($reward_config['reach_num'] * $gain_car_num));
                                GoodsModel::update(['car_reward_tip' => 1], [['goods_id', 'IN', $need_goods_id]]);
                            }
                        }

                        $stock =  (new GoodsModel)->where('activity_id',$order->activity_id)
                            ->where(['status' => 0,'box_index' => $order_goods[0]['box_index']])
                            ->count();
                        if($stock == 0){
                            Log::channel('wxpay')->info('刚好买完这箱,系统自动分配选择车位,并将未选择的车位也进行一并选择');
                            $car_reward_data = CarReward::where([
                                'activity_id' => $order->activity_id,
                                'reward_id' => $reward_config['reward_id'],
                                'box_index' => $order_goods[0]['box_index'],
                                'status' => 0,
                            ])->select()->toArray();
                            Log::channel('wxpay')->info('更新所有未选择车位:'.count($car_reward_data));
                            foreach ($car_reward_data as  $item){
                                $remain_index = app(TwiceRward::class)->getStockCarNUmber($order->activity_id,$order_goods[0]['box_index'],$reward_config['reward_id']);
                                Log::channel('wxpay')->info('车位剩余：'.json_encode($remain_index));
                                $car_reward = CarReward::where('id',$item['id'])->find();
                                $car_reward->select_index = $remain_index[0];
                                $car_reward->select_time = time();
                                $car_reward->status = 1;
                                $car_reward->save();
                            }
                            //特殊奖缓存库存
                            Cache::store('redis')->set($order->activity_id.'#'.$order_goods[0]['box_index'],1,10);
                        }

                    }
                }
            }
            Db::commit();
            Log::channel('wxpay')->info('结束处理车位奖');
            return true;
        }catch (\Exception $e){
            Log::channel('wxpay')->info('车位处理失败：'.$e->getMessage());
            return false;
        }
    }


    public function callSuccess()
    {
        // 用户订单
        Queue::push("app\\job\\LuckyBagQueue", ['order_no' => $this->order_no], LuckyBagQueue::QUEUE);
        // 活动奖励
        Queue::push("app\\job\\LuckyBagReward", ['order_no' => $this->order_no], LuckyBagReward::QUEUE);
    }
}